package com.xcap.security.datasourceauthentication.vo;

import com.xcap.security.datasourceauthentication.entity.SysUser;
import com.xcap.security.datasourceauthentication.service.impl.SysMenuService;
import com.xcap.security.datasourceauthentication.service.impl.SysUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.AccountExpiredException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SecurityUserDetailsService implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getSysUserByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username+"用户不存在");
        }
        if (sysUser.getAccountNoExpired()!=1){
            try {
                throw new AccountExpiredException("账户过期异常");
            } catch (AccountExpiredException e) {
                throw new RuntimeException(e);
            }
        }
        List<String> userPermissions = sysMenuService.queryPermissionsByUserId(sysUser.getUserId());

        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (String permission : userPermissions) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(permission));
        }
      //  List<SimpleGrantedAuthority> collect = userPermissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        MySecurityUser securityUser = new MySecurityUser(sysUser);
        securityUser.setAuthorities(simpleGrantedAuthorities);
        return securityUser;
    }
}
